<template>
  <div class="employees">
    <div class="app-container">
      <head-tool>
        <div class="btns" slot="after">
          <el-button type="success" size="small" @click="outExcel">
            <i class="el-icon-document-remove"></i>
            导出</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="
              $router.push({ path: '/import', query: { type: 'employees' } })
            "
          >
            <i class="el-icon-document"></i> 导入</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="showDialog = true"
            >新增员工</el-button
          >
        </div>
      </head-tool>
      <el-card>
        <el-table :data="tableData" border>
          <!-- 序号 -->
          <el-table-column
            label="序号"
            type="index"
            width="120px"
          ></el-table-column>
          <!-- 姓名 -->
          <el-table-column
            prop="username"
            label="姓名"
            width="120px"
          ></el-table-column>
          <el-table-column label="头像">
            <template slot-scope="{ row }">
              <!-- <div>{{ row.staffPhoto }}</div> -->
              <img
                :src="row.staffPhoto"
                @click="qrCode(row.staffPhoto)"
                v-imgerror="staffPhoto"
                width="60px"
                height="60px"
              />
            </template>
          </el-table-column>
          <!-- 手机号 -->
          <el-table-column
            prop="mobile"
            label="手机号"
            width="120px"
          ></el-table-column>
          <!-- 工号 -->
          <el-table-column prop="workNumber" label="工号"></el-table-column>
          <!-- 聘用形势 -->
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            width="120px"
          >
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <!-- 入职时间 -->
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
          ></el-table-column>
          <!-- 部门 -->
          <el-table-column prop="departmentName" label="部门"></el-table-column>
          <!-- 转正时间 -->
          <el-table-column
            prop="correctionTime"
            label="转正时间"
          ></el-table-column>
          <!-- 状态 -->
          <el-table-column prop="enableState" label="状态">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240px" fixed="right">
            <div
              slot-scope="{ row }"
              style="display: flex; justify-content: space-between"
            >
              <el-link
                size="small"
                type="primary"
                @click="
                  $router.push({
                    path: '/empinfo',
                    query: { id: row.id }
                  })
                "
                >查看</el-link
              >
              <el-link size="small" type="primary">转正</el-link>
              <el-link size="small" type="primary">调岗</el-link>
              <el-link size="small" type="primary">离职</el-link>
              <el-link size="small" type="primary" @click="setRole(row.id)"
                >角色</el-link
              >
              <el-link size="small" type="primary" @click="del(row.id)">
                删除</el-link
              >
            </div>
          </el-table-column>
        </el-table>
        <el-pagination
          @current-change="handleCurrentChange"
          :page-size="pageInfo.size"
          :current-page="pageInfo.page"
          :total="pageInfo.total"
          layout="total,prev, pager, next"
        />
      </el-card>
    </div>

    <!-- 弹窗 -->
    <adduser :showDialog="showDialog" />
    <!-- 二维码弹窗 -->
    <el-dialog title="二维码" :visible.sync="dialogVisible" width="30%">
      <el-row type="flex" justify="center">
        <canvas ref="canvas"></canvas>
      </el-row>
    </el-dialog>
    <!-- 角色分配弹窗 -->
    <rolesetting
      :showRoleDialog.sync="showRoleDialog"
      :currentId="roleId"
      ref="roles"
    />
  </div>
</template>
<script>
// 获取员工信息列表,删除员工接口
import { getStaffList, delStaff } from '@/api/employees'
// 导入枚举工具
import constant from '@/api/constant/employees'
// 导入子组件
import adduser from './components/add-user.vue'
import rolesetting from './components/role-setting.vue'
//导入二维码组件
import qrcode from 'qrcode'

export default {
  name: 'emp',
  //注册子组件
  components: {
    adduser,
    rolesetting
  },
  data () {
    return {
      staffPhoto: require('@/assets/common/zwt.jpg'),
      // 员工信息
      tableData: [],
      //绑定Dialog弹窗
      showDialog: false,
      //二维码弹窗
      dialogVisible: false,
      //角色弹窗
      showRoleDialog: false,
      //角色Id
      roleId: '',
      //分页数据
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  // vue生命周期钩子
  created () {
    this.getuser()
  },
  methods: {
    // 获取员工列表数据
    async getuser () {
      let res = await getStaffList(this.pageInfo)
      // console.log(res)
      this.tableData = res.data.rows
      this.tableData.forEach(item => {
        item.enableState = item.enableState == 1 ? true : false
      })
      this.pageInfo.total = res.data.total
    },
    // 删除事件
    async del (id) {
      try {
        await this.$confirm('确认删除吗？')
        // 通过id发请求删除员工
        await delStaff(id)
        // 刷新数据
        this.getuser()
        //提示
        this.$message.success('删除成功')
      } catch (error) {
        //提示
        this.$message('取消成功')
      }
    },
    //分页点击事件
    handleCurrentChange (page) {
      // 把切换后的页码赋值给 pageInfo.page
      this.pageInfo.page = page

      // 然后根据最新的pageInfo去加载数据
      this.getuser()
    },
    //导出Excel
    async outExcel () {
      let res = await getStaffList({
        page: 1,
        size: this.pageInfo.total
      })
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      let keys = Object.keys(headers)

      let bigArr = res.data.rows.map(item => {
        let arr = []
        for (let key in headers) {
          let engKey = headers[key]
          if (key == '聘用形式') {
            let srt = item[engKey] == 1 ? '正式' : '未知'
            arr.push(srt)
          } else {
            arr.push(item[engKey])
          }
        }
        return arr
      })

      //导出功能也不是一个非常常用的功能，所以使用的时候建议使用懒加载。使用方法如下：
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: keys, //表头 必填
          data: bigArr, //具体数据 必填
          filename: '员工信息表格', //非必填
          autoWidth: true, //非必填
          bookType: 'xlsx' //非必填
        })
      })
    },
    //二维码
    qrCode (url) {
      if (url) {
        this.dialogVisible = true
        this.$nextTick(() => {
          console.log(this.$refs.canvas)
          qrcode.toCanvas(this.$refs.canvas, url)
        })
      } else {
        this.$message.warning('该员工没有图片！')
      }
    },
    //分配角色
    setRole (id) {
      this.showRoleDialog = true
      this.roleId = id
      this.$refs.roles.getUserProfile(id)
    }
  },
  // 过滤器
  filters: {
    formatHireType (val) {
      let list = constant.hireType.filter(item => item.id == val)
      return list[0] ? list[0].value : '未知'
    }
  }
}
</script>

<style scoped></style>
